import { Service } from 'egg';
import { Setting } from '../model/Setting';

export default class SettingService extends Service {
    /**
     * 查找系统设置
     * @param param 
     */
    public async searchSetting(param: any) {
        try {
            const { setting_key } = param;
            const result: any = await this.ctx.model.Setting.findOne<Setting>({ attributes: ['setting_value'], where: { setting_key, is_delete: '0' } });
            if (!result) {
                throw new Error(JSON.stringify({ code: 1, msg: '没有找到该设置' }));
            }
            return result;
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 操作注册状态
     * @param param 
     */
    public async settingRegisterStatus(param: any) {
        try {
            const { setting_key, setting_value } = param;
            const result: any = await this.ctx.model.Setting.update({ setting_value }, { where: { setting_key } });
            if (result[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
            }
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }
}